<template>
  <div class="TheTimer">
    <span>{{ hours }}:</span>
    <span>{{ mins }}:</span>
    <span>{{ secs }}</span>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  name: 'the-timer',
  props:{
    time:{
      type:String,
      default:'',
    }
  },
  data () {
    return {
      days:'',
      hours:'',
      mins:'',
      secs:'',
      timer:null
    }
  },
  watch:{
    time:{
      handler(){
        if(this.timer) clearInterval(this.timer)
        this.showTimeIncrease()
      },
      immediate:true
    }
  },
  methods: {
    // 正计时
    showTimeIncrease(){
      let totalSecs = moment().diff(this.time, 'second');
      this.timer = setInterval(() => {
        let days = this.toDouble( Math.floor(totalSecs / 3600 / 24));
        let hours = this.toDouble(Math.floor((totalSecs - days * 24 * 3600) / 3600));
        let mins = this.toDouble(Math.floor((totalSecs - days * 24 * 3600 - hours * 3600) / 60));
        let secs = this.toDouble(Math.floor((totalSecs - days * 24 * 3600 - hours * 3600 - mins * 60)));
        this.days = days
        this.hours = this.toDouble(parseInt(days * 24) + parseInt(hours))
        this.mins = mins
        this.secs = secs
        totalSecs++;
      }, 1000);
    },
    toDouble(num){
      if(num < 10){
        return `0${num}`;
      }
      return num;
    }
  },
  destroyed(){
    clearInterval(this.timer)
  }
}
</script>

<style scoped lang="scss"></style>
